package com.example.springboot2209.Controller;

import com.example.springboot2209.entity.User;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.ArrayList;
import java.util.List;

/**
 * @Name: UserController
 * @Date: 2023/10/25 22:27
 * @Author: 西风残叶
 */
@Controller
public class UserController {
    private static File userDir;

    static {
        // 创建文件用于保存注册信息
        userDir = new File("./users");
        if (!userDir.exists()) {
            userDir.mkdirs();
        }
    }

    /**
     * 动态请页面
     * @param request:请求数据
     * @param response:发送数据
     */
    @RequestMapping("/userList")
    public void userList(HttpServletRequest request, HttpServletResponse response){
        System.out.println("开始处理动态页面......");
        /*
         * 1.将user中的所有 obj文件获取
         * 2.将文件逐一反序列化得到一组user对象
         * 3.拼接html页面
         * 4.发送
         */
        File[] subs = userDir.listFiles(f -> f.getName().endsWith(".obj"));
        List<User> userList = new ArrayList<>();
        for (File sub: subs) {

            try (FileInputStream fis = new FileInputStream(sub);
                 ObjectInputStream ois =new ObjectInputStream(fis);){
                User user = (User) ois.readObject();
                userList.add(user);
            } catch (IOException e) {
                throw new RuntimeException(e);
            } catch (ClassNotFoundException e) {
                throw new RuntimeException(e);
            }
        }
        userList.forEach(System.out::println);
        try {
            // 设置页面的字符集为utf-8
            response.setContentType("text/html;charset=utf-8");
            PrintWriter pw = response.getWriter();
            pw.println("<!DOCTYPE html>");
            pw.println("<html lang=\"en\">");
            pw.println("<head>");
            pw.println("<meta charset=\"UTF-8\">");
            pw.println("<title>用户列表</title>");
            pw.println("</head>");
            pw.println("<body>");
            pw.println("<center>");
            pw.println("<h1>用户列表</h1>");
            pw.println("<table border='1'>");
            pw.println("<tr>");
            pw.println("<td>用户名</td>");
            pw.println("<td>密码</td>");
            pw.println("<td>昵称</td>");
            pw.println("<td>年龄</td>");
            pw.println("</tr>");
            for (User user: userList) {
                pw.println("<tr>");
                pw.println("<td>"+user.getUsername()+"</td>");
                pw.println("<td>"+user.getPassword()+"</td>");
                pw.println("<td>"+user.getNickname()+"</td>");
                pw.println("<td>"+user.getAge()+"</td>");
                pw.println("</tr>");
            }
            pw.println("</table>");
            pw.println("</center>");
            pw.println("</body>");
            pw.println("</html>");
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    @RequestMapping("/regUser")
    public void reg(HttpServletRequest request, HttpServletResponse response) {
        /**
         * 请求对象HttpServletRequest:表示浏览器提交上来的所有内容
         * 相应对象HttpServletResponse:表示服务器要给浏览器回复的内容
         */
        System.out.println("开始处理用户注册!!!!!!!!!");
        // 1.通过request对象获取注册油漆面表单提交的注册信息
        // HttpServletRequest提供了获取参数的方法,参数就是form表单中的名字
        String username = request.getParameter("username");
        String password = request.getParameter("password");
        String nickname = request.getParameter("nickname");
        String ageStr = request.getParameter("age");
        // 做必要的检验工作
        if (username == null || username.isEmpty() || password == null || password.isEmpty()
                || nickname == null || nickname.isEmpty() || !ageStr.matches("[0-9]+")) {
            try {
                response.sendRedirect("/reg_info_error.html");
                return;
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        }
        System.out.println(username + "," + password + "," + nickname + "," + ageStr);
        int age = Integer.parseInt(ageStr);
        // 2.将该注册用户信息保存
        // 在userDir的表示的目录中纯碱指定名字的文件
        File f = new File(userDir, username + ".obj");
        if (f.exists()) {
            try {
                response.sendRedirect("/have_user.html");
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
            return;

        }
        User user = new User(username, password, nickname, age);
        try (FileOutputStream fos = new FileOutputStream(f);
             ObjectOutputStream oos = new ObjectOutputStream(fos)
        ) {
            oos.writeObject(user);
            // 3.通过response响应注册结果页面
            response.sendRedirect("/reg_success.html");
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    @RequestMapping("/loginUser")
    public void login(HttpServletRequest request, HttpServletResponse response) {
        System.out.println("开始登录了!!!!!!!!!!");
        // 获取输入的密码和用户名
        String username = request.getParameter("username");
        String password = request.getParameter("password");
        File file = new File(userDir, username + ".obj");
        // System.out.println(file.exists());

        if (file.exists()) { // 判断文件是否存在
            if (username == null || username.isEmpty() || password == null || password.isEmpty()) {
                try {
                    response.sendRedirect("/login_info_error.html");
                    return;
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }
            }
            try (FileInputStream fis = new FileInputStream(file);
                 // 使用ObjectInputStream进行反序列化
                 ObjectInputStream ois = new ObjectInputStream(fis);
            ) {
                User line = (User) ois.readObject();
                if (password.equals(line.getPassword())) {
                    response.sendRedirect("/login_success.html");
                    return;
                } else {
                    response.sendRedirect("/login_fail.html");
                    return;
                }
            } catch (IOException | ClassNotFoundException e) {
                throw new RuntimeException(e);
            }
        }
        // 文件不存在的情况
        try {
            response.sendRedirect("/login_unuser.html");
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
}